<template>
  <div>
    <Drawer
      ref="modal"
      width="70%"
      :title="`${editType === 'create' ? $t('newDevices.addPerson') : $t('areaIndex.areaAddBtnEdit')}`"
      :value="show"
      :beforeClose="$_modal_decideIfClose"
    >
      <Form
        ref="form"
        :labelWidth="100"
        :model="formData"
        :rules="formRule"
      >
        <FormItem :label="$t('AccessIndex.AccessJobdeNum')">
          <div class="item" style="float:left;margin-right:40px">
            <Cascader :data="recordTypes" v-model="recordType"
              @on-change="handleChange1" :clearable="false"
              change-on-select>
            </Cascader>
          </div>
        </FormItem>
        <FormItem class="personList" prop="mids" :label="$t('areaIndex.areaAddBindMan')">
          <div class="action">
            <div class="itemTitle">
              <Checkbox class="checkBox"
                :value="allCheck"
                @on-change="handleSlectAll"
              >{{ $t("areaIndex.areaSearchAll") }}</Checkbox>
              <div class="num">
                <span>{{departName}}{{ $t("newDevices.total") }}{{ personList.length }}{{ $t("BodyTemperatureIndex.BodyTemAnimalMan") }}</span>&nbsp&nbsp&nbsp&nbsp
                <span>{{ $t("devicesIndex.devSelected") }}{{ checkDNum }}</span>
              </div>
            </div>
            <div class="itemTitle ml">
              <div class="num">
                <!-- <span>{{departName}}{{ $t("newDevices.total") }}{{ personList.length }}{{ $t("BodyTemperatureIndex.BodyTemAnimalMan") }}</span>&nbsp&nbsp&nbsp&nbsp -->
                <span>{{ $t("areaIndex.areaSearchSelected") }}{{ formData.mids.length }}</span>
              </div>
            </div>
            
          </div>
          <div class="list" ref="personList">
            <div class="person-list"  >
              <RecycleScroller
                class="scroller person-item"
                :items="personList"
                :item-size="32"
                key-field="mid"
                v-slot="{ item }"
                :prerender="10"
                v-show="personList.length>0"
              >
                <div class="user">
                  <Checkbox
                    :value="item.checked"
                    @on-change="itemChange(item,item.checked)"
                  />
                  <Icon class="item-icon" type="md-contact" size="24" />
                  <div class="item-title">{{ item.username }}</div>
                  
                </div>
              </RecycleScroller>
              <div class="pl" v-show="personList&&personList.length<=0">{{this.$t('areaIndex.areaSearchNoData')}}</div>
            </div>
            <div class="person-list ml">
              <RecycleScroller
                class="scroller person-item"
                :items="formData.mids"
                :item-size="32"
                key-field="mid"
                v-slot="{ item }"
                v-show="formData.mids.length>0"
                :prerender="10"
              >
                <div class="user">
                  <Icon class="item-icon" type="md-contact" size="24" />
                  <div class="item-title">{{ item.username }}</div>
                  <!-- <template v-slot="{ index }">
                    <Icon class="close-icon" @click="delPerson(item,index)" type="md-close-circle" size="22" />
                  </template> -->
                  <Icon class="close-icon" @click="delPerson(item)" type="md-close-circle" size="22" />
                </div>
              </RecycleScroller>
              <div class="pl" v-show="formData.mids&&formData.mids.length<=0">{{this.$t('areaIndex.areaSearchNoData')}}</div>
            </div>
          </div>
          
        </FormItem>
        <FormItem class="glo-btn-group">
          <Button
            type="primary"
            :loading="loading"
            @click="handleSubmit"
          >{{ $t("devicesCreate.devCreateSubmit") }}</Button>
          <Button
            @click="$_modal_close"
          >{{ $t("devicesCreate.devCreateCancel") }}</Button>
        </FormItem>
      </Form>
    </Drawer>
  </div>
</template>

<script>
import _ from 'lodash'
import {
  mapState,
} from 'vuex'

import modalMixin from '@/utils/mixins/modalMixin.js'
import {
  areaBindPerson,
  // create,
  update,
  detail,
} from '@/api/area.js'
import {
  // getList,
  selectAllPerson
} from '@/api/person.js'

import Vue from 'vue'
import { RecycleScroller } from 'vue-virtual-scroller'

Vue.component('RecycleScroller', RecycleScroller)
import "vue-virtual-scroller/dist/vue-virtual-scroller.css";

const DEFAULT_FORM = {
  // areaName: '',
  mids: [
    // { mid: 1, username: '陈一' },
    // { mid: 2, username: '陈二' },
    // { mid: 3, username: '陈三' },
  ],
}

export default {
  mixins: [
    modalMixin,
  ],
  // components: {
    // PeopleSelect,
    // VueVirtualScroller
  // },

  props: {
    editType: {
      type: String,
      default: 'create',
    },
    editItem: Object,
  },
  data () {
    return {
      ifAdvanced: true,
      formData: _.cloneDeep(DEFAULT_FORM),
      formRule: {
        // mids: { required: true, message: this.$t('Attendance.AttendanceSelNum') },
      },
      recordTypes: [],
      recordType: [],
      personList:[],
      depId:'',
      departName:'',
      // defaultPersonList:[],
      //滚动事件相关
      // clientHeight:'',
      // scrollTop:'',
      // scrollPersonList:[],
      // currentPage:1,//当前页
    }
  },
  computed: {
    ...mapState([
      'departId',
    ]),
    allCheck() {
      if(!this.personList||this.personList.length<=0){
        return false
      }else{
        // every 当数组中每一项都返回 true，整体才返回 true；有一项返回 false，整体就返回 false
        return this.personList.every(item => {
          return item.checked
        })
      } 
    },
    checkDNum() {
      if(!this.personList){
        return 0
      }else{
        // every 当数组中每一项都返回 true，整体才返回 true；有一项返回 false，整体就返回 false
        let num=0
        this.personList.map(item => {
          if(item.checked){
            num++
          }
        })
        return num
      } 
    }
  },
  // watch: {
  //   personList:{
  //     handler(newName, oldName) {
  //       // 
  //       this.personList.forEach(v=>{
  //         console.log(v)
          
  //         if(v.checked&&this.defaultPersonList.includes(v.mid)==false){
  //           console.log('fuhe')
  //           let data={
  //             mid:v.mid,username:v.username
  //           }
  //           this.formData.mids.push(data)
  //         }
  //       })
      
  //   　},
  //     deep: true,
  //   　immediate: true
  //   }
  // },
  mounted () {
    this.show = true
    // if (this.editType === 'update') {
      this.getDetail()
      this.getDataList()
    // }
  },

  methods: {
    async handleSubmit () {
      const ifVlid = await this.$refs.form.validate()
      if (ifVlid && this.editType === 'create') {
        this.handleCreate()
      }
      if (ifVlid && this.editType === 'update') {
        this.handleUpdate()
      }
    },

    async getDetail () {
      let areaId=window.sessionStorage.getItem('tableId')||''
      const { success, data } = await detail({ areaId })
      if (success) {
        const netForm = data.data
        const formData = {}
        const keys = Object.keys(DEFAULT_FORM)
        keys.forEach(key => {
          formData[key] = _.isUndefined(netForm[key])
            ? DEFAULT_FORM[key]
            : netForm[key]
        })
        formData.id = netForm.id
        if(netForm.midList){
          formData.mids = netForm.midList
        }else{

        }
        // let arr=[]
        // formData.mids.forEach(v=>{
        //   arr.push(v.mid)
        // })
        // this.defaultPersonList=arr
        // console.log('this.defaultPersonList',this.defaultPersonList)
        this.formData = _.cloneDeep(formData)
      }
    },
    async handleCreate () {
      let areaId1=window.sessionStorage.getItem('tableId')||''
      let areaId=Number(areaId1)
      let data2=[];
      this.formData.mids.forEach(v=>{
        let da={
          areaId:areaId,mid:v.mid
        }
        data2.push(da)
      })
      // console.log('mid',data2)
      // return
      const { success } = await areaBindPerson(data2)
      if (success) {
        this.$Message.success(this.$t('devicesCreate.devCreateS'))
        this.ifUpdateUpper = true
        this.$_modal_close()
      } else {
        this.$Message.error(this.$t('Attendance.AttendanceSelNum'))
        // this.$Message.error(this.$t('devicesCreate.devCreateN'))
      }
    },
    async handleUpdate () {
      const formData = _.cloneDeep(this.formData)
      formData.departId = this.departId
      const { success } = await update(formData)
      if (success) {
        this.$Message.success(this.$t('devicesCreate.devCreateUpdateS'))
        this.ifUpdateUpper = true
        this.$_modal_close()
      } else {
        this.$Message.error(this.$t('devicesCreate.devCreateUpdateN'))
      }
    },
    async getDataList () {
      // 通过vuex调接口获取公司名depart是vuex中别的一套vuex模块
      const list = await this.$store.dispatch('depart/getList')
      let listString = JSON.stringify(list).replace(/"id"/g, '"value"')
      let listStringLabel = listString.replace(/"departName"/g, '"label"')
      let listStringChildren = listStringLabel.replace(/"children"/g, '"children"')
      var aParse = JSON.parse(listStringChildren)
      function dG(params) {
        params.forEach(v=>{
          if(v.children){
            dG(v.children)
          }else{
            v.children=[]
          }
        })
      }
      dG(aParse)
      if(aParse[0].label==="新部门"){
        let arr12 = aParse
        arr12[0].label=this.$t('title.newDepart')
        this.recordTypes=arr12
      }else{
        this.recordTypes = aParse
      }

      console.log('this.recordTypes23')
      console.log(this.recordTypes)
      
      setTimeout(()=>{
        let arr=[]
        arr.push(this.recordTypes[0].value) 
        this.recordType = arr
        if(!this.depId){
          // console.log('this.depId2',this.depId)
          this.depId=this.recordTypes[0].value
        }
        if(!this.departName){
          console.log('this.departName',this.departName)
          this.departName=this.recordTypes[0].label
          console.log('this.departName',this.departName)
        }
        this.getAllPersonList()
        // console.log('recordType',this.recordType)
      },500)
    },
    handleChange1 (value,selectedData) {     
      if(value.length>0){
        // this.recordType = value
        // console.log(value)
        // console.log(selectedData)
        this.personList=[]
        this.currentPage=1
        this.depId=value[value.length-1]
        this.departName=selectedData[selectedData.length-1].label
        this.getAllPersonList()
      }else{
        // this.depId=''
        // this.getData()
      } 
    },
    async getAllPersonList () {
      let result = []
      console.log('this.depId',this.depId)
      
      const { success, data } = await selectAllPerson({
          depId:this.depId,
          // depId:'727',
          // page,
          // limit,
          // isTable,
        })
        if (success && data) {
          let res=data.data
          let midList=[]
          if(this.formData.mids.length>0){
            this.formData.mids.forEach(item=>{
              midList.push(item.mid)
            })
          }
          res.forEach(v=>{
            if(midList.includes(v.mid)){
              v.checked=true
            }else{
              v.checked=false
            }
          })
          this.personList=res
        }
    },
    handleSlectAll(e){
      if(this.personList){
        var da='',arr=[]
        // let data= this.formData.mids
        // let data= JSON.parse(JSON.stringify(this.formData.mids))
        this.personList.forEach(item => {
          // arr.push(item.mid)
          if(e){
            if(!item.checked){
              da={
                mid:item.mid,username:item.username
              }
              this.formData.mids.push(da)
            }else{

            }
            
          }else{
            arr.push(item.mid)
          }
          item.checked=e
        })
        // if(e){
        //   data=Array.from(new Set(data))
        //   // console.log('data',data)
        // }
        // else if(!e){
        //   // console.log('ARR',arr)
        //   data=data.filter((v,i)=> {
        //     return !arr.includes(v.mid)
        //   })
        //   console.log('全不选',data)
        // }
        if(!e){
          this.formData.mids=this.formData.mids.filter((v,i)=> {
            return !arr.includes(v.mid)
          })
        }
        // this.formData.mids=data
        // this.formData.mids=new Set(this.formData.mids)
        // this.formData.mids.forEach((v,i)=> {
        //   // if(!e&&arr.includes(v.mid)){
        //   //     this.formData.mids.splice(i,1)
        //   // }else if(e)
        //   if(arr.includes(v.mid)){
        //     if(!e){
        //       this.formData.mids.splice(i,1)
        //     }else{

        //     }
        //     //选择组里面有
        //   }else{
        //     if(e){
        //       this.formData.mids.push(da)
        //     }
        //   }
        // })
      }
    },
    itemChange(item,checked){
      //checked之前的选择状态
      // console.log('checked',item,checked)
      item.checked=!item.checked
      let da={
        mid:item.mid,username:item.username
      }
      // console.log(da)
      if(checked){
        this.formData.mids.forEach((v,i)=> {
          if(v.mid==item.mid){
            //选择组里面有
            this.formData.mids.splice(i,1)
          }
        })
      }else{
        this.formData.mids.push(da)
      }
    },
    delPerson(item){
      // alert(index)
      this.formData.mids.forEach((v,i)=> {
        if(v.mid==item.mid){
          this.formData.mids.splice(i,1)
        }
      })
      this.getAllPersonList()
    }
  },
  
}
</script>
<style lang="less" scoped>
.personList{
  // width: 80%;
  .action{
    height: 32px;
    display: flex;
      align-items: center;
    .itemTitle{
      width: 45%;
      display: inline-block;
      // display: flex;
      // align-items: center;
      &.ml{
        margin-left: 3%;
      }
      .num{
        float: right;
        margin-right: 10px;
      }
    }
    
  }
  .list {
    // flex: 1;
    // height: 400px;
    // overflow: auto;
    box-sizing: border-box;
    padding: 10px 0;
    
    .person-list{
      float: left;
      width: 45%;
      height: 400px;
      box-sizing: border-box;
      border: 1px solid #ccc;
      &.ml{
        margin-left: 3%;
      }
      .pl{
        padding-left: 10px;
        
        // text-align: center;
      }
      .person-item{
        .item-icon{
          vertical-align: middle;
        }
        .item-title{
          // display: inline;
          display: inline-block;
          margin-left: 10px;
          white-space: nowrap;
          text-overflow: ellipsis;
          overflow: hidden;
        }
        .close-icon{
          // float: right;
          flex: 1;
          text-align: right;
        }
      }
    }
  }
}
.scroller {
  // height: 100%;
  height: 400px;
}

.user {
  height: 32%;
  padding: 0 12px;
  display: flex;
  align-items: center;
} 
</style>
